package org.example.server.user.service;

import cn.hutool.core.util.IdUtil;
import cn.hutool.crypto.digest.DigestUtil;
import cn.hutool.jwt.JWTUtil;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.example.server.user.bean.AccountBean;
import org.example.server.user.mapper.AccountMapper;
import org.springframework.stereotype.Service;

import java.util.HashMap;

@Slf4j
@Service
public class AccountService {

    @Resource
    private AccountMapper accountMapper;

    public void register(AccountBean accountBean) {
        log.debug("用户注册，检查参数");
        if (accountBean.getUsername() == null){
            throw new RuntimeException("用户名不能为空");
        }
        if (accountBean.getPassword()==null){
            throw new RuntimeException("密码不能为空");
        }
        if (!accountBean.getPassword().equals(accountBean.getRePassword())){
            throw new RuntimeException("两次密码不一致");
        }

        log.debug("用户注册，检查用户名是否已存在");
        AccountBean requestBean = new AccountBean();
        requestBean.setUsername(accountBean.getUsername());
        AccountBean resultBean = accountMapper.selectOne(requestBean);
        if (resultBean != null){
            throw new RuntimeException("用户名已存在");
        }

        log.debug("用户注册，补充参数");
        //雪花算法生成id
        accountBean.setId(IdUtil.getSnowflakeNextId());
        //将密码进行重新编码
        accountBean.setPassword(DigestUtil.md5Hex(accountBean.getPassword()));
        accountBean.setUpdateTime(System.currentTimeMillis());
        accountBean.setCreateTime(System.currentTimeMillis());

        log.debug("用户注册，操作sql语句");
        int inserted = accountMapper.insert(accountBean);
        if (inserted < 1){
            throw new RuntimeException("注册失败");
        }
    }

    public String login(AccountBean accountBean) {
        log.debug("用户登录, 检查参数");
        if (accountBean.getUsername() == null){
            throw new RuntimeException("用户名不能为空");
        }
        if (accountBean.getPassword()==null){
            throw new RuntimeException("密码不能为空");
        }
        log.debug("用户登录, 查询数据库");
        AccountBean resultBean = accountMapper.selectOne(accountBean);
        if (resultBean == null){
            throw new RuntimeException("用户名或密码错误");
        }
        String password = DigestUtil.md5Hex(accountBean.getPassword());
        if (!password.equals(resultBean.getPassword())){
            throw new RuntimeException("用户名或密码错误");
        }

        byte[] key = "hanchun123".getBytes();
        HashMap<String, Object> map = new HashMap<>();
        map.put("id",resultBean.getId());
        map.put("updateTime",System.currentTimeMillis());
        return JWTUtil.createToken(map,key);
    }

}
